package com.situ.mall.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.situ.mall.base.config.AlipayConfigBean;
import com.situ.mall.base.entity.OrderInfo;
import com.situ.mall.base.service.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * ClassName: PayServiceImpl
 * Package: com.situ.mall.base.service.impl
 * Description:
 *
 * @Author Darling_达
 * @Create 2023-04-11 17:24
 * @Version 1.0
 */

@Service
public class PayServiceImpl implements IPayService {

    @Autowired
    private AlipayConfigBean alipayConfigBean;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String createPayOrder(OrderInfo order) {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigBean.getUrl(), alipayConfigBean.getAppid(), alipayConfigBean.getPrivateKey(), "json", "UTF-8", alipayConfigBean.getAlipayPublicKey(), alipayConfigBean.getSignType());
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl("https://71n848l850.yicp.fun/order/notify");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getCode());
        bizContent.put("total_amount", order.getPrice());
        bizContent.put("subject", "测试商品");

        request.setBizContent(bizContent.toString());
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("调用成功");
                return response.getQrCode();
            } else {
                System.out.println("调用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ""; // 返回支付二维码
    }

    @Override
    public void payResult(Map<String, String> params) {

    }

}
